﻿using log4net;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Libraries.Postgresql;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.Models.Trade;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace PlaceOrder_Core.Services.Instances
{
    public class DataHelper:IDataHelper
    {
        public static BaseConfigModel BaseConfig;
        public static ILog _log;
        public static IDatabase _database;

        public static List<TSInfoRow> TsInfos;
        public static decimal DefaultPVBP;

        #region 静态字段初始化
        public List<TSInfoRow> GetAllTSInfo()
        {
            List <TSInfoRow> ts = new List<TSInfoRow> ();
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return ts; // 返回一个空列表
                    }

                    ts = db.Tsinfos
               .Where(ts => (bool)!ts.Deleted)
               .OrderByDescending(ts => ts.Tscode)
               .Select(ts => new TSInfoRow
               {
                   id = ts.Id,
                   tsCode = ts.Tscode,
                   StartDate = ts.Startdate,
                   BondKey = ts.Bondkey,
                   LastDayCrawled = ts.Lastdaycrawled,
                   BondName = ts.Bondname,
                   ListedMarket = ts.Listedmarket,
                   BondRating = ts.Bondrating,
                   IssueRate = ts.Issuerate,
                   IssueAmount = ts.Issueamount,
                   IssuePrice = ts.Issueprice,
                   Maturity = ts.Maturity,
                   MaturityDate = ts.Maturitydate,
                   BondFullName = ts.Bondfullname,
                   RealTime = ts.Realtime ?? false,
                   InterestPerYear = (int)ts.Interestperyear,
                   FirstTradeDate = ts.Firsttradedate ?? DateOnly.MinValue,
                   InterestDate = ts.Intereststartdate ?? DateOnly.MinValue,
                   QBDate = ts.Qbdate ?? DateOnly.FromDateTime(DateTime.Now),
                   LastdayCrawledTime = ts.Lastdaycrawledtime ?? DateTime.MinValue,
                   PoolId = (int)ts.Poolid,
                   PVBP = (decimal)ts.Basicvalue,
                   HengShengMarketID = ts.HengshengId,
                   HengShengMarketName = ts.HengshengName
               })
               .ToList();


                }

            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "GetAllTSInfo" + ex.StackTrace);
            }
            return ts;
         }
        #endregion
        public DataHelper(ILog log,IDatabase database)
        {
   
            _database = database;
            if (!File.Exists("base_config.ini"))
            {
                AppLog.WriteInfo("配置文件不存在");
                return;
            }
            if (BaseConfig == null)
            {
                try
                {
                    BaseConfig = new BaseConfigModel();
                    StreamReader sr = new StreamReader("base_config.ini");
                    BaseConfig.ConnectionString = sr.ReadLine() + $"ApplicationName = PlaceOrder_SERVER";
                    BaseConfig.HttpUrl = sr.ReadLine();
                    BaseConfig.WebSocketUrl = sr.ReadLine();
                    BaseConfig.LilyHttpUrl = sr.ReadLine();
                    sr.Close();

                    IdbhostContext.SqlStr = BaseConfig.ConnectionString;
                }
                catch(Exception ex)
                {
                    AppLog.WriteInfo("配置文件读取异常"+ex.Message);
                    return;
                }
            }

            Init();
        }
        private void Init()
        {
            //0831
            //TsInfos = GetAllTSInfo();
            //DefaultPVBP = GetLastTopTrade();
        }

        public decimal GetLastTopTrade()
        {
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                       
                        return 1;
                    }

                    var query = (from t in db.TradekchartId9s
                                 where t.Tradedate < DateOnly.FromDateTime(DateTime.Today)
                                 group t by new { t.Tscode, t.Volume, t.Tradedate } into g
                                 orderby g.Key.Tradedate descending, g.Key.Volume descending
                                 select new
                                 {
                                     TsCode = g.Key.Tscode,
                                     Volume = g.Key.Volume
                                 }).FirstOrDefault();

                    if (query != null)
                    {
                        var ts = db.Tsinfos.SingleOrDefault(x => x.Tscode == query.TsCode);
                        if (ts != null)
                        {
                            return (decimal)ts.Basicvalue;
                        }
                    }

                    return 1;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"{ex.Message} DataHelper GetLastTopTrade. {ex.StackTrace}");
                return 1;
            }
        }


        #region 客户端相关接口实现
        public List<UserTradeVolumeConfig> GetUserTradeVolumeConfig(int userId)
        {
            List<UserTradeVolumeConfig> volumes = new List<UserTradeVolumeConfig>();
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return volumes;
                    }
                    volumes = db.UserTradeVolumeConfigs
                             .Where(o => o.UserId == userId)
                             .ToList();

                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message + "DataHelper" + "GetUserTradeVolumeConfig" + ex.StackTrace);
            }
            return volumes;
        }

        #endregion
    }
}
